<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 创客管理
 */
namespace app\allwin\controller;
use app\common\facade\Inform;
use app\common\model\SystemUser;
use app\allwin\model\AllwinUser;
use app\allwin\model\VipCard;
use app\allwin\model\Vip;
use think\facade\Request;
use think\facade\Validate;
use think\helper\Time;

class VipUser extends Common{

    public function initialize() {
        parent::initialize();
        $this->assign('pathMaps',[['name'=>'创客设置','url'=>url("vip/index")]]);
    }

    /**
     * 
     * @param int $types
     * @param int $vip_id
     * @return type
     */
    public function index(int $types = 0,int $vip_id = 0){
        $vip_class = [];
        $vip       = [];
        $condition = [];
        $vip_class = VipCard::where($this->mini_program)->order('sort desc,id desc')->select();
        if($vip_id > 0){
            $condition[] = ['vipcard_id','=',$vip_id];
        }
        $time      = Request::param('time/d',0);
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['update_time','>=',$start];
            $condition[] = ['update_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['update_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['update_time','<=',strtotime($endtime)];
            }
        }
        $view['store_vipnum']   =  Vip::where($this->mini_program)->where($condition)->where('store_id','>',0)->count();  //好店会员数量
        $view['platform_vipnum'] = Vip::where($this->mini_program)->where($condition)->where('store_id','=',0)->count(); //平台会员数量
        $condition[] = ['state','=',1];
        $store_id = Request::param('store_id/d','');
        $store_name = Request::param('store_name/s','');
        if($store_id){
            $condition[] = ['store_id','=',$store_id];
        }
        $view['vipnum']    = Vip::where($this->mini_program)->where($condition)->count();           //会员数量
        $view['vipamount'] = Vip::where($this->mini_program)->where($condition)->sum('amount');  //支付金额
        //用户精准查询
        $uid = Request::param('uid/d','');
        if($uid){
            $condition[] = ['user_id','=',$uid];
        }
        //锁定或正常
        $condition[] = ['is_lock','=',$types ? 1 : 0];
        $view['lists']  = Vip::where($this->mini_program)->where($condition)->order('id desc')->paginate(20,false,['query'=> ['types' => $types,'vip_id' => $vip_id]]);
        //模板赋值
        $view['pathMaps'][]   = ['name'=>' 会员会员','url'=>url('vip_user/index')];
        if ($vip_id > 0) {
            $vip = VipCard::where(['id' => $vip_id])->field('name,id')->find();        
            $view['pathMaps'][] = ['name' => $vip->name,'url'=>url('vip_user/index',['vip_id' => $vip->id])];
        }
        $view['pathMaps'][] = ['name'=>$types ? '<span class="red fn-fb">锁定<span>' : '<span class="blue fn-fb">正常<span>','url'=>'javascript:;'];
        $view['vip']        = $vip;
        $view['vip_class']  = $vip_class;
        $view['types']      = $types;
        $view['vip_id']     = $vip_id;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        $view['store_id']   = $store_id;
        $view['store_name'] = $store_name;
        $view['uid']        = $uid;
        return view()->assign($view);
    }
    
    /**
     * 添加创客会员
     * @return type
     */
    public function winUser(){
        if(request()->isAjax()){
            $uids = ids(input('post.ids/s'),true);
            if(empty($uids)){
                return json(['code'=>0,'msg'=>'请选择要关联的用户']);
            }
            $vip_id  = input('get.vip_id/d');
            $vipcard = VipCard::where($this->mini_program)->where(['id' => $vip_id])->find();
            if(empty($vipcard)){
                return json(['code'=>0,'msg'=>'未找到对应会员']);
            }
            //读取并判断是否VIP
            $vipdata  = [];
            $userdata = [];
            foreach ($uids as $key => $uid) {
                $vipdata[$key]['order_no']    = 'Platform'.date('YmdhHis');
                $vipdata[$key]['state']       = 1;
                $vipdata[$key]['coupon_ids']  = json_encode([]);
                $vipdata[$key]['amount']      = 0;
                $vipdata[$key]['is_up']       = $vipcard->is_up;  
                $vipdata[$key]['vipcard_id']  = $vipcard->id;
                $vipdata[$key]['update_time'] = time();
                $vipdata[$key]['is_lock']     = 0;
                $vipdata[$key]['is_diy']      = 1;
                $vipdata[$key]['store_id']    = 0;   //邀请参数的店铺ID
                $vipdata[$key]['user_id']     = $uid;
                $vipdata[$key]['member_miniapp_id'] = $this->member_miniapp_id;
                $is_user = AllwinUser::where(['uid'=> $uid])->find();
                if(empty($is_user)){
                    $userdata[] = ['uid' =>$uid,'store_id' => 0];
                }
                //通知到申请者微信
                Inform::sms($uid,$this->member_miniapp_id,['title' =>'业务进展通知','type' => '身份变更','state' => '成功','content' =>'您的身份已变更为'.$vipcard['name']]);
            }
            //锁定以前的会员
            Vip::where(['user_id' => $uids,'state' => 1])->update(['is_lock' => 1]);
            Vip::insertAll($vipdata);
            if(!empty($userdata)){
                AllwinUser::insertAll($userdata);
            }
            return json(['code'=>200,'msg'=>'会员用户新增成功','data' => ['url'=>'']]);
        }else{
            $vip_id = input('get.vip_id/d');
            $view['vip'] = VipCard::where($this->mini_program)->where(['id' => $vip_id])->find();
            if(empty($view['vip'])){
                $this->error('未找到会员类型');
            }
            $keyword = trim(input('get.keyword','','htmlspecialchars'));
            $condition = [] ;
            if(!empty($keyword)){
                if(Validate::isMobile($keyword)){
                    $condition[] = ['phone_uid','=',$keyword] ;
                }else{
                    $condition[] = ['nickname','like','%'.$keyword.'%'];
                }
            }       
            $view['list'] = SystemUser::where($this->mini_program)->where($condition)->where('id', 'NOT IN', function ($query) use($vip_id){ 
                $query->table('ai_allwin_vip')->where(['state' => 1,'vipcard_id' => $vip_id])->field('user_id');
            })->order('id desc')->paginate(20,false,['query' => ['keyword'=>$keyword,'vip_id' => $vip_id]]);
            $view['keyword'] = $keyword;
            $view['vip_id']  = $vip_id;
            return view()->assign($view);
        }
    }

    /**
     * 删除用户的优惠券
     * @return void
     */
    public function deleteUser(){
        $uid = input('get.uid/d');
        $result = Vip::where($this->mini_program)->where(['user_id' => $uid])->delete();
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        }
    }

    /**
     * 开通会员的社交关系
     * @return void
     */
    public function level(int $id){
        $agent = model('AllwinUser')->where(['uid' => $id])->find();
        if(!$agent){
            return $this->error("404 NOT FOUND");
        }
        $data['nickname']    = $agent->user->nickname;
        $data['invite_code'] = $agent->user->invite_code;
        $data['phone_uid']   = $agent->user->phone_uid;
        $data['face']        = $agent->user->face;
        $data['store_name']  = empty($agent->store->name) ? '[无店铺]会员' : $agent->store->name;
        $data['level']       = 0;
        $view['user']        = $data;
        $view['level']       = model('Levels')->children_user($id);
       
        return view()->assign($view);
    }
}